package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //  后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());


        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void insertUser(EmployeeDTO dto) {


        log.info("EmployeeServiceImpl 新增员工");
//        创建一个employee实体类，用来保存数据
        Employee employee = new Employee();

//        复制属性(属性名要一模一样)
        BeanUtils.copyProperties(dto,employee);


//        补充未添加的数据，创建时间等
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

//谁登陆了 谁修改了，就应该存谁的id
        Long currentId = BaseContext.getCurrentId();

        log.info("当前员工id：{},Service 层  当前线程id：{}", currentId,Thread.currentThread().getId());

//        employee.setCreateUser(currentId); // 固定数据，有问题---改成动态数据
//        employee.setUpdateUser(currentId);

        employee.setStatus(StatusConstant.ENABLE);

//        密码加密 初始密码123456--->md5
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        插入


        employeeMapper.insertUser(employee);



    }

    @Override
    public Employee getEmployeeByUsername(String username) {
        return   employeeMapper.getEmployeeByUsername(username);
    }

    @Override
    public PageResult pageByCondition(EmployeePageQueryDTO queryDTO) {

//        开启分页
        PageHelper.startPage(queryDTO.getPage(),queryDTO.getPageSize());

//        处理name  aha
        if(queryDTO.getName()!=null) {
            queryDTO.setName(queryDTO.getName().trim());
        }


        Page<Employee> employees=employeeMapper.pageByCondition(queryDTO);


//        创建结果集

        PageResult pageResult = new PageResult();
        pageResult.setTotal(employees.getTotal());
        pageResult.setRecords(employees.getResult());


        return pageResult;
    }

    @Override
    public void changeStatus(Integer status, Long id) {

//        禁用和启用要不要修改时间


        employeeMapper.updateStatusById(status,id);

    }

    @Override
    public Employee getById(Long id) {



        return employeeMapper.getById(id);
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {

//        EmployeeDTO 转成实体类 Employee
        Employee employee = Employee.builder().build();

//        源数据  目标对象
        BeanUtils.copyProperties(employeeDTO,employee);

//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());

//        employee对象 没有密码，没有状态 没有创建时间 没有创建人


        employeeMapper.updateById(employee);




    }

}
